package com.dpj.visibility_test;

import lombok.extern.slf4j.Slf4j;


//两阶段终止模式(优雅的终止)  使用volatile关键字
@Slf4j(topic = "c.TwoPhaseDemo")
public class TwoPhaseDemo {

    public static void main(String[] args) throws InterruptedException {

        TwoPhaseTermination tpt=new TwoPhaseTermination();
        tpt.start();
        Thread.sleep(3500);
        tpt.stop();

    }


}

@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination{
    //监控线程
    private Thread monitor;

    //停止标记
    private  volatile boolean stop;
    //启动监控线程
    public void start(){
        monitor=new Thread(()->{
            while (true){
                Thread thread = Thread.currentThread();
                if(stop){

                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);//
                    log.debug("执行监控记录");//
                } catch (InterruptedException e) {

                }
            }
        });
        monitor.start();
    }
    //停止监控线程
    public void stop(){
        stop=true;
        monitor.interrupt();
    }
}

